<?php
/* This file is part of a copyrighted work; it is distributed with NO WARRANTY.
 * See the file COPYRIGHT.html for more details.
 */
 
require_once("../shared/global_constants.php");
require_once("../classes/Section.php");
require_once("../classes/Query.php");

/******************************************************************************
 * MemberQuery data access component for library members
 *
 * @author David Stevens <dave@stevens.name>;
 * @version 1.0
 * @access public
 ******************************************************************************
 */
class SectionQuery extends Query {
  var $_itemsPerPage = 1;
  var $_rowNmbr = 0;
  var $_currentRowNmbr = 0;
  var $_currentPageNmbr = 0;
  var $_rowCount = 0;
  var $_pageCount = 0;

  function setItemsPerPage($value) {
    $this->_itemsPerPage = $value;
  }
  function getCurrentRowNmbr() {
    return $this->_currentRowNmbr;
  }
  function getRowCount() {
    return $this->_rowCount;
  }
  function getPageCount() {
    return $this->_pageCount;
  }

  /****************************************************************************
   * Executes a query
   * @param string $type one of the global constants
   *               OBIB_SEARCH_BARCODE or OBIB_SEARCH_NAME
   * @param string $word String to search for
   * @param integer $page What page should be returned if results are more than one page
   * @access public
   ****************************************************************************
   */
  function execSearch($type, $word, $page) {
    # reset stats
    $this->_rowNmbr = 0;
    $this->_currentRowNmbr = 0;
    $this->_currentPageNmbr = $page;
    $this->_rowCount = 0;
    $this->_pageCount = 0;

    # Building sql statements
    if ($type == OBIB_SEARCH_CUE) {
      $col = "cue";
    } elseif ($type == OBIB_SEARCH_NAME) {
      $col = "name";
    }

    # Building sql statements
    $sql = $this->mkSQL("from Section where %C like %Q ", $col, $word."%");
    $sqlcount = "select count(*) as rowcount ".$sql;
    $sql = "select * ".$sql;
    $sql .= " order by cue";
    # setting limit so we can page through the results
    $offset = ($page - 1) * $this->_itemsPerPage;
    $limit = $this->_itemsPerPage;
    $sql .= $this->mkSQL(" limit %N, %N ", $offset, $limit);
    #echo "sql=[".$sql."]<br>\n";

    # Running row count sql statement
    $rows = $this->exec($sqlcount);
    if (count($rows) != 1) {
      Fatal::internalError("Wrong number of count rows");
    }
    # Calculate stats based on row count
    $this->_rowCount = $rows[0]["rowcount"];
    $this->_pageCount = ceil($this->_rowCount / $this->_itemsPerPage);

    # Running search sql statement
    $this->_exec($sql);
  }

  /****************************************************************************
   * Executes a query
   * @param string $sectionid Section id of library member to select
   * @return boolean returns false, if error occurs
   * @access public
   ****************************************************************************
   */
  function get($sectionid) {
    $sql = $this->mkSQL("select * from section "
                        . "where sectionid = %N ", $sectionid);
    $rows = $this->exec($sql);
    if (count($rows) != 1) {
      Fatal::internalError("Bad Sectionid");
    }
    return $this->_mkObj($rows[0]);
  }
  
  /****************************************************************************
   * Executes a query
  * @param string $claveon section id of library member to select
  * @return boolean returns false, if error occurs
  * @access public
  ****************************************************************************
  */  
  function getByClaveOne($claveone) {
  	$sql = $this->mkSQL("select * from section "
  			. "where claveone = %Q ", $claveone);
  	$rows = $this->exec($sql);
  	if (count($rows) != 1) {
  		return null;
  	}
  	return $this->_mkObj($rows[0]);
  }  
  
  function maybeGetByName($name) {
    $sql = $this->mkSQL("select * from Section "
                        . "where barcode_nmbr=%Q ", $bcode);
    $row = $this->select01($sql);
    if($row)
      return $this->_mkObj($row);
    return NULL;
  }

  /****************************************************************************
   * Fetches a row from the query result and populates the Section object.
   * @return Section returns library member or false if no more members to fetch
   * @access public
   ****************************************************************************
   */
  function fetchSection() {
    $array = $this->_conn->fetchRow();
    if ($array == false) {
      return false;
    }
    # increment rowNmbr
    $this->_rowNmbr = $this->_rowNmbr + 1;
    $this->_currentRowNmbr = $this->_rowNmbr + (($this->_currentPageNmbr - 1) * $this->_itemsPerPage);
    return $this->_mkObj($array);
  }
  function _mkObj($array) {
    $Section = new Section();
    $Section->setSectionId($array["sectionid"]);
    $Section->setName($array["name"]);
    $Section->setSchoolId($array["schoolid"]);
    $Section->setStudents($array["students"]);
    $Section->setTurnoId($array["turnoid"]);
    $Section->setYear($array["year"]);
    $Section->setApply($array["apply_flg"]);
    $Section->setClaveOne($array["claveone"]);

    return $Section;
  }
  
  /****************************************************************************
   * Returns true if barcode number already exists
   * @param string $barcode Library member barcode number
   * @param string $sectionid Library member id
   * @return boolean returns true if barcode already exists
   * @access private
   ****************************************************************************
   */
  function DupClaveOne($claveone, $sectionid=0) {
    $sql = $this->mkSQL("select count(*) as num from section "
                        . "where claveone = %N and sectionid <> %N",
                        $claveone, $sectionid);
    $rows = $this->exec($sql);
    if (count($rows) != 1) {
      Fatal::internalError('Bad number of rows');
    }
    if ($rows[0]['num'] > 0) {
      return true;
    }
    return false;
  }

  /****************************************************************************
   * Inserts a new library member into the member table.
   * @param Section $Section library member to insert
   * @return integer the id number of the newly inserted member
   * @access public
   ****************************************************************************
   */
  function insert($Section) {
    $sql = $this->mkSQL("insert into section "
                        . "(sectionid,  "
                        . " year, name, turnoid, students, "
                        . " schoolid, apply_flg, claveone) "
                        . "values (null, %N, %Q, "
                        . " %N, %N, %N, %Q, %Q) ",
                        $Section->getYear(), $Section->getName(),
                        $Section->getTurnoId(), $Section->getStudents(), 
    					$Section->getSchoolId(), $Section->getApply(),
						$Section->getClaveOne());

    $this->exec($sql);
    $sectionid = $this->_conn->getInsertId();
    return $sectionid;
  }

  /****************************************************************************
   * Update a library member in the member table.
   * @param Section $Section library member to update
   * @access public
   ****************************************************************************
   */
  function update($Section) {
    $sql = $this->mkSQL("update section set "
                        . " year = %N, name=%Q, "
                        . " turnoid=%N,  students=%N,  schoolid=%N, "
    					. " apply_flg=%Q,  claveone=%Q "
                        . "where sectionid=%N",
                        $Section->getYear(), $Section->getName(),
                        $Section->getTurnoId(), $Section->getStudents(),
						$Section->getSchoolId(),$Section->getApply(),
    					$Section->getClaveOne(),
    					$Section->getSectionId());
    $this->exec($sql);
  }
  
  /****************************************************************************
   * Update a library member in the member table.
  * @param Section $Section library member to update
  * @access public
  ****************************************************************************
  */
  function updateWithMember($Section) {
  	$sql = $this->mkSQL("update section set "
  			. " year = %N, name=%Q, "
  			. " turnoid=%N,  students=%N,  schoolid=%N, "
  			. " apply_flg=%Q,  claveone=%Q, mbrid=%N "
  			. "where sectionid=%N",
  			$Section->getYear(), $Section->getName(),
  			$Section->getTurnoId(), $Section->getStudents(),
  			$Section->getSchoolId(),$Section->getApply(),
  			$Section->getClaveOne(),$Section->getMbrid(),
  			$Section->getSectionId());
  	$this->exec($sql);
  }  

  /****************************************************************************
   * Deletes a library member from the member table.
   * @param string $sectionid Member id of library member to delete
   * @access public
   ****************************************************************************
   */
  function delete($sectionid) {
    $sql = $this->mkSQL("delete from section where sectionid = %N ", $sectionid);
    $this->exec($sql);
  }
  
  function desvincularByMbrid($mbrid){
  	$sql = $this->mkSQL("update section set mbrid = 0 where mbrid = %N ", $mbrid);
  	$this->exec($sql);  	
  }
  
  function desvincularBySection($sectionid){
  	$sql = $this->mkSQL("update section set mbrid = 0 where sectionid = %N ", $sectionid);
  	$this->exec($sql);
  }  
  
}

?>
